//
//  LGOutPlayBar.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/3/31.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit
import ReactiveSwift


protocol LGOutPlayBarDelegate {
    func didSongStartPlay(_ song:Song) -> Void
    func didSongPause(_ song:Song) -> Void
    func didSongContinue(_ song:Song) -> Void
    func didSongProcess(_ song:Song, _ progress:Double, _ currentDuration:Double, _ totoalDuration:Double) -> Void
}


var single = LGOutPlayBar.customPlayBar()

class LGOutPlayBar: UIView {

    public var delegate:LGOutPlayBarDelegate?
    var playOrPauseButton:UIButton?
    var nextButton:UIButton?
    var previousButton:UIButton?
    var iconImageView:UIImageView?
    var titleLabel:UILabel?
    var subTitleLabel:UILabel?
    var playingId:String?
    var songs:[Song]?
    var progressView:UIView?
    var progress:Float?
    var currentIndex:Int? {
        didSet{
            self.loadMusic((self.songs?[currentIndex!])!)
        }
    }

    class func customPlayBar() -> LGOutPlayBar {
        let customPlayBar = LGOutPlayBar.init(frame: CGRect.zero)
        customPlayBar.configure()
        return customPlayBar
    }

    //单例
    class var sharedBar:LGOutPlayBar {
        return single
    }

    /// 重载数据
    let playingIdKey = "playingId"
    func loadData() -> Void {

        if let playIndexValue = UserDefaults.standard.value(forKey: playingIdKey) as? String{
            self.playingId = playIndexValue
        }
        SongFMDBHelper.getFavoriteSongs { (songs) in
            self.songs = songs
            if (self.songs?.count)! > 0 {
                if self.playingId == nil {
                    self.playingId = self.songs?[0].songId
                }
                var index = 0
                for  song:Song in self.songs! {
                    if song.songId == self.playingId {
                        self.currentIndex = index
                        break
                    }
                    index += 1
                }
                if self.currentIndex == nil {
                    self.currentIndex = 0
                }
            }
        }
    }

    /// //加载UI
    ///
    /// - Parameter song:
    func loadMusic(_ song:Song) -> Void {
        self.iconImageView?.sd_setImage(with: URL.init(string: (song.songPicRadio)!), completed: { (image, error, type, url) in
            if error == nil { //成功
                MusicPlayerManager.sharedInstance.configMusicInfo(song.songName!, artist: song.artistName!, coverImage: image)
            }
        })
        self.titleLabel?.text = song.songName
        self.subTitleLabel?.text = song.artistName
    }


    /// 跳转到主播放界面
    func transitionToDetail() {
        if ((self.songs?.count) != 0) {
            let billCtrl = BillDetailViewController()
            billCtrl.song = (self.songs?[self.currentIndex!])!
            SMNAVI_PRESENT(billCtrl)
        }
    }


    func configure() {

        /// 添加跳转手势
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(LGOutPlayBar.transitionToDetail))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tapGesture)

        self.backgroundColor = UIColor.white
        self.iconImageView = UIImageView.init(image: UIImage.init(named: "ic_playbar_album"))
        self.addSubview(self.iconImageView!)
        self.iconImageView?.snp.makeConstraints { (make) in
            make.left.top.equalTo(SM_SIZE(5))
            make.bottom.equalTo(SM_SIZE(-5))
            make.width.equalTo((self.iconImageView?.snp.height)!)
        }

        self.titleLabel = UILabel.init()
        self.titleLabel?.font = SM_CFont(15)
        self.titleLabel?.textColor = SM_HEXCOLOR("030303")
        self.addSubview(self.titleLabel!)
        self.titleLabel?.snp.makeConstraints({ (make) in
            make.left.equalTo(self.iconImageView!.snp.right).offset(SM_SIZE(15))
            make.top.equalTo(self.iconImageView!.snp.top).offset(SM_SIZE(9))
        })

        self.subTitleLabel = UILabel.init()
        self.subTitleLabel?.font = SM_CFont(12)
        self.subTitleLabel?.textColor = SM_HEXCOLOR("818181")
        self.addSubview(self.subTitleLabel!)
        self.subTitleLabel?.snp.makeConstraints({ (make) in
            make.left.equalTo(self.titleLabel!.snp.left)
            make.top.equalTo(self.titleLabel!.snp.bottom).offset(SM_SIZE(5))
        })

        let buttonMargin = SM_SIZE(20)
        self.nextButton = UIButton.init()
        self.nextButton?.setImage(UIImage.init(named:"btn_next"), for: UIControlState.normal)
        self.nextButton?.setImage(UIImage.init(named:"btn_next_dis"), for: UIControlState.highlighted)
        self.nextButton?.addTarget(self, action: #selector(self.nextSong), for: UIControlEvents.touchUpInside)
        self.addSubview(self.nextButton!)
        self.nextButton?.contentEdgeInsets = UIEdgeInsets(top: buttonMargin, left: buttonMargin, bottom: buttonMargin, right: buttonMargin)
        self.nextButton?.snp.makeConstraints({ (make) in
            make.right.equalTo(SM_SIZE(-20))
            make.centerY.equalTo(self.snp.centerY)
        })

        self.playOrPauseButton = UIButton.init()
        self.playOrPauseButton?.setImage(UIImage.init(named: "btn_bofang"), for: UIControlState.normal)
        self.playOrPauseButton?.setImage(UIImage.init(named: "btn_bofang_dis"), for: UIControlState.highlighted)
        self.playOrPauseButton?.setImage(UIImage.init(named: "btn_zanting"), for: UIControlState.selected)
        self.playOrPauseButton?.addTarget(self, action: #selector(self.playOrPauseButtonTap(_:)), for: UIControlEvents.touchUpInside)
        self.addSubview(self.playOrPauseButton!)
        self.playOrPauseButton?.contentEdgeInsets = UIEdgeInsets(top: buttonMargin, left: buttonMargin, bottom: buttonMargin, right: buttonMargin)
        self.playOrPauseButton?.snp.makeConstraints({ (make) in
            make.right.equalTo((self.nextButton?.snp.left)!).offset(SM_SIZE(0))
            make.centerY.equalTo(self.snp.centerY)
        })

        self.previousButton = UIButton.init()
        self.previousButton?.setImage(UIImage.init(named:"btn_next"), for: UIControlState.normal)
        self.previousButton?.setImage(UIImage.init(named:"btn_next_dis"), for: UIControlState.highlighted)
        self.previousButton?.transform = CGAffineTransform.init(rotationAngle: CGFloat(Double.pi))
        self.previousButton?.addTarget(self, action: #selector(self.lastSong), for: UIControlEvents.touchUpInside)
        self.addSubview(self.previousButton!)
        self.previousButton?.contentEdgeInsets = UIEdgeInsets(top: buttonMargin, left: buttonMargin, bottom: buttonMargin, right: buttonMargin)
        self.previousButton?.snp.makeConstraints({ (make) in
            make.right.equalTo((self.playOrPauseButton?.snp.left)!).offset(SM_SIZE(0))
            make.centerY.equalTo(self.snp.centerY)
        })


        let view = UIView.init()
        view.backgroundColor = SM_HEXCOLOR("eaeaea")
        self.addSubview(view)
        view.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(0)
            make.height.equalTo(1)
        }

        self.progressView = UIView.init()
        self.progressView?.backgroundColor = SM_HEXCOLOR("3ECD89")
        self.addSubview(self.progressView!)
        self.progressView?.snp.makeConstraints({ (make) in
            make.left.bottom.equalTo(0)
            make.height.equalTo(2.5)
            make.width.equalTo(SM_SCREEN_SIZE().width*0.0)
        })

        NotificationCenter.default.addObserver(self, selector: #selector(self.loadData), name: NSNotification.Name(rawValue: SM_SONG_FAVORITE_LIST_DID_CHANGE_NOTIFICATION), object: nil)
        self.loadData()


    }


    /// 播放、继续、暂停
    ///
    /// - Parameter sender:
    func playOrPauseButtonTap(_ sender:UIButton) -> Void {
        self.playOrPauseButton?.isSelected = !(self.playOrPauseButton?.isSelected)!
        if (!(self.playOrPauseButton?.isSelected)!) {
            self.pasue()
        }else {
            if MusicPlayerManager.sharedInstance.status == MusicPlayerManager.ManagerStatus.pause {
                self.goOn()
            }else {
                self.startPlay()
            }
        }

    }


    /// 开始播放
    func startPlay() {
        if self.songs?.count == 0 {
            return
        }
        self.playOrPauseButton?.isSelected = true
        UserDefaults.standard.set(self.songs?[self.currentIndex!].songId, forKey: playingIdKey)

        //callback song.startplay
        if (self.delegate != nil) {
            self.delegate?.didSongStartPlay((self.songs?[self.currentIndex!])!)
        }

        MusicPlayerManager.sharedInstance.play(URL.init(string: (self.songs?[self.currentIndex!].songLink!)!)) {[weak self] (tmpProgress, playProgress) in
            if (playProgress != nil) {
                func updateContraints() {
                    self?.progressView?.snp.updateConstraints({ (make) in
                        make.width.equalTo(SM_SCREEN_SIZE().width*CGFloat(playProgress!))
                    })
                }

                func checkStatus() {
                    // callback song.process
                    if ((self?.delegate) != nil) {
                        if (self?.currentIndex)! + 1 <= (self?.songs?.count)! {
                            self?.delegate?.didSongProcess((self!.songs?[self!.currentIndex!])!, Double(playProgress!), Double(MusicPlayerManager.sharedInstance.playTime), Double(MusicPlayerManager.sharedInstance.playDuration))
                        }
                    }

                    if MusicPlayerManager.sharedInstance.status == MusicPlayerManager.ManagerStatus.stop || playProgress == 1.0 {
                        self?.nextSong()
                    }
                }

                if Thread.isMainThread {
                    updateContraints()
                    checkStatus()
                }else {
                    DispatchQueue.main.async {
                        updateContraints()
                        checkStatus()
                    }
                }
            }
        }
    }

    //中止
    public func stop() {
        MusicPlayerManager.sharedInstance.stop()
    }

    //暂停
    public func pasue() {
        self.playOrPauseButton?.isSelected = false
        MusicPlayerManager.sharedInstance.pause()
        //callback song.pause
        if (self.delegate != nil) {
            self.delegate?.didSongPause((self.songs?[self.currentIndex!])!)
        }
    }

    //继续播放
    public func goOn() {
        self.playOrPauseButton?.isSelected = true
        MusicPlayerManager.sharedInstance.goOn()
        //callback song.continue||song.goon
        if (self.delegate != nil) {
            self.delegate?.didSongContinue((self.songs?[self.currentIndex!])!)
        }
    }

    //下一曲
    public func nextSong() {
        var indexToBe = self.currentIndex! + 1
        if indexToBe >= (self.songs?.count)!  {
            indexToBe = 0
        }
        var index = self.currentIndex! 
        while index == self.currentIndex! {
            index = Int(arc4random()%UInt32((self.songs?.count)!))
        }
        indexToBe = index
        self.playSong(at: indexToBe)
    }

    //上一曲
    public func lastSong() {
        var indexToBe = self.currentIndex! - 1
        if indexToBe < 0  {
            indexToBe = (self.songs?.count)! - 1
        }
        self.playSong(at: indexToBe)
    }
    
    public func playSong(at index:Int) {
        self.currentIndex = index
        self.checkToPlay()
    }
    
    private func checkToPlay() {
        self.startPlay()
    }
    
    
}



